package com.gnerv.battle.boot.module.base.interceptor.mybatis;

import com.gnerv.battle.boot.common.base.annotation.tenant.TenantExclude;
import com.gnerv.battle.boot.common.tools.ReflectTools;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author Gnerv LiGen
 */
@Intercepts({
        @Signature( type = Executor.class, method = "update",args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
@Component
public class BattleTenantMybatisInterceptor implements Interceptor {

    private final BattleTenantInvocationHandler battleTenantInvocationHandler = new BattleTenantInvocationHandler();
    private final BattleTenantSqlParserHandler battleTenantSqlParserHandler = new BattleTenantSqlParserHandler();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        String id = ms.getId();
        TenantExclude annotation = AnnotationUtils.findAnnotation(ReflectTools.getMethod(id), TenantExclude.class);
        if (annotation != null) {
            return invocation.proceed();
        }
        String sql = battleTenantInvocationHandler.getSql(invocation);
        sql = battleTenantSqlParserHandler.handle(sql);
        battleTenantInvocationHandler.setSql(invocation, sql);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
